package com.sso.login.controller;

import com.sso.login.pojo.User;
import com.sso.login.utils.LoginCache;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

/**
 * @Author:LuJiaHong
 * @Date:2021/2/18~20:51:10
 * @Version 1.0
 *登录判断，页面跳转
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    private static Set<User> dbUsers;
    static {
        dbUsers=new HashSet<>();
        dbUsers.add(new User(1,"tom","666"));
        dbUsers.add(new User(2,"jack","777"));
        dbUsers.add(new User(3,"lisa","888"));
    }
    @PostMapping
    public String doLogin(User user, HttpSession session, HttpServletResponse response){
        //获取发起登录页面的IP地址
        String target = (String) session.getAttribute("target");
        //模拟从数据库中通过登录的用户名和密码去查找数据库中的用户
        Optional<User> first = dbUsers.stream().filter(dbUser -> dbUser.getUsername().equals(user.getUsername()) &&
                dbUser.getPassword().equals(user.getPassword()))
                .findFirst();
        //判断用户是否登录
        if(first.isPresent()){
        //登录成功,保存用户登录信息
            String token = UUID.randomUUID().toString();
            //添加cookie对象
            Cookie cookie = new Cookie("TOKEN",token);
                //cookie在子系统间访问，要求域名相同
                cookie.setDomain("lujiahong.com");
            //响应到子系统
            response.addCookie(cookie);
            LoginCache.loginUser.put(token,first.get());
        }else {
            //登录失败
            session.setAttribute("msg","用户名或密码错误");
            return "login";
        }
        //重定向到target地址
        return "redirect:"+target;
    }

    /**
     * 通过cookie（token）获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/info")
    @ResponseBody
    public ResponseEntity<User> getUserInfo(String token){
        if(!StringUtils.isEmpty(token)){
            User user = LoginCache.loginUser.get(token);
            return ResponseEntity.ok(user);
        }else{
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }
}
